#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>

using namespace std;

class Solution {
private:
    map<char, char> w2pMap{};
    map<char, char> p2wMap{};

public:
    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
        vector<string> ret{};

        for (const auto& word : words) {
            if (word.length() != pattern.length()) {
                break;
            }

            w2pMap.clear();
            p2wMap.clear();
            bool flag = true;
            for (size_t idx = 0; idx < word.length(); idx++) {
                auto itorW2p = w2pMap.find(word[idx]);
                auto itorP2w = p2wMap.find(pattern[idx]);

                if ((itorW2p == w2pMap.end()) && (itorP2w == p2wMap.end())) {
                    w2pMap.insert(make_pair(word[idx], pattern[idx]));
                    p2wMap.insert(make_pair(pattern[idx], word[idx]));
                } else if ((itorW2p != w2pMap.end()) && (itorP2w != p2wMap.end())) {
                    if ((itorW2p->second != pattern[idx]) || (itorP2w->second != word[idx])) {
                        flag = false;
                        break;
                    }
                } else {
                    flag = false;
                    break;
                }
            }

            if (flag) {
                ret.emplace_back(word);
            }
        }

        return ret;
    }
};

template<typename T>
void ShowVectorElem(T elems)
{   
    for (const auto& elem : elems) {
        cout << elem << " ";
    }
    cout << endl;
}

int main() 
{
    Solution s;
    vector<string> vt{"abc","deq","mee","aqq","dkd","ccc"};
    string pat = "abb";
    const vector<string>& ret = s.findAndReplacePattern(vt, pat);
    ShowVectorElem(ret);

    return 0;
}